package com.lobaby.tools.fx.controller;

import com.lobaby.tools.fx.init.JavaConsole;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Rectangle2D;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebEvent;
import javafx.scene.web.WebView;
import netscape.javascript.JSObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.URL;
import java.util.ResourceBundle;

/**
 * @author Administrator
 *         Created by Administrator on 2021/2/25 0025.
 */
@Component
public class WebviewController implements Initializable {
    @Value("${config.initurl}")
    private String initUrl;

    @FXML
    private WebView webView;

    @FXML
    private ProgressIndicator progressIndicator;

    @Autowired
    private JavaConsole console;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        setUrl(initUrl);
        WebEngine webEngine = webView.getEngine();
        webEngine.setOnResized((WebEvent<Rectangle2D> event) -> {
            // To change body of generated methods, choose Tools | Templates.
            System.out.println("Window resized");
        });

        webEngine.getLoadWorker().stateProperty().addListener((observable, oldValue, newValue) ->
        {
            if ("SUCCEEDED".equals(newValue.toString())) {
                progressIndicator.setVisible(false);

                JSObject window = (JSObject) webEngine.executeScript("window");
                window.setMember("java", console);
//                webEngine.executeScript("console.log = function(message)\n" +
//                        "{\n" +
//                        "    java.log(message);\n" +
//                        "};");
            } else {
                progressIndicator.setVisible(true);
            }
        });
    }

    public void setUrl(String url) {
        // show process indicator
//		webView.setVisible(false);
        progressIndicator.setVisible(true);

        // load html page
        WebEngine webEngine = webView.getEngine();
//        webEngine.load(WebviewController.class.getResource(url).toExternalForm());
        webEngine.load(url);
    }

}